package com.example.riceexambackend.controller.handler;

import com.example.riceexambackend.common.errorcode.CommonErrorCodeConstants;
import com.example.riceexambackend.common.exception.ControllerException;
import com.example.riceexambackend.common.exception.ServiceException;
import com.example.riceexambackend.common.pojo.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理器
 * @author ricejson
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(ServiceException.class)
    public CommonResult<?> serviceException(ServiceException e) {
        // 打错误日志
        logger.error("ServiceException: " + e);
        // 封装错误信息
        return CommonResult.fail(CommonErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), e.getMsg());
    }

    @ExceptionHandler(ControllerException.class)
    public CommonResult<?> controllerException(ControllerException e) {
        // 打错误日志
        logger.error("ControllerException: " + e);
        // 封装错误信息
        return CommonResult.fail(CommonErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult<?> exception(Exception e) {
        // 打错误日志
        logger.error("Exception: " + e);
        e.printStackTrace();
        // 封装错误信息
        return CommonResult.fail(CommonErrorCodeConstants.INTERNAL_SERVER_ERROR);
    }
}
